package cn.coopen.italktv.networkcheckdemo;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class NetWorkCheckService extends Service {
	private static final String TAG ="NetWorkCheckService";
	public static final String NET_RECOVERY_ACTION = "cn.coopen.italktv.netconnect";
	public static final String CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
	public static final String serverUrlStr = "http://epg20.italktv.colnv.com/v300/service/network";
	private ScheduledExecutorService es;//线程池
	private CheckRunnable checkRunable;


	@Override
	public IBinder onBind(Intent intent) {
		// TODO: Return the communication channel to the service.
		throw new UnsupportedOperationException("Not yet implemented");
	}

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println(this.getClass().getSimpleName() + ":onCreate");
		checkRunable = new CheckRunnable(this);
		es = Executors.newSingleThreadScheduledExecutor();
		if (isNetworkAvailable(this))
		es.scheduleAtFixedRate(checkRunable,5,40, TimeUnit.SECONDS);
	}

//		booleanFutureTask = new FutureTask<Boolean>(new CheckCallable()){
//			@Override
//			protected void done() {
//				try {
//					Boolean result = booleanFutureTask.get();
//					System.arraycopy(results,1,results,0,1);//左移1位
//					results[1]=result;
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				} catch (ExecutionException e) {
//					e.printStackTrace();
//				}finally {
//					isCheckingConnect = false;
//				}
//			}
//		};



	@Override
	public int onStartCommand(Intent intent,int flags, int startId) {
		System.out.println(this.getClass().getSimpleName() + ":onStartCommand");
		if (isNetworkAvailable(this)&&es.isShutdown())
			es.scheduleAtFixedRate(checkRunable,5,40, TimeUnit.SECONDS);
		return START_STICKY;
	}

	public  boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null && info.isConnected())
			{
				// 当前网络是连接的
				if (info.getState() == NetworkInfo.State.CONNECTED)
				{
					// 当前所连接的网络可用
					return true;
				}
			}
		}
		return false;
	}

	public static class CheckRunnable implements Runnable{
		private boolean[] results = new boolean[]{true,true};
		private Context mContext;

		public CheckRunnable(Context mContext) {
			this.mContext = mContext;
		}


		@Override
		public void run() {
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10*1000);
			HttpConnectionParams.setSoTimeout(httpParams, 10*1000);
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			String url = serverUrlStr;
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response;
			boolean isConnect = false;
			int count = 0;
			while (count < 2 ) {
				Log.d(TAG, "count========" + count);
				count++;
				try {
					response = httpclient.execute(httpPost);
					int resultCode = response.getStatusLine().getStatusCode();
					Log.d(TAG, "resultCode========" + resultCode);
					if (resultCode == 200 || resultCode == 301 || resultCode == 302) {
						isConnect = true;
						break;
					}
					Thread.sleep(2000);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			System.arraycopy(results,1,results,0,1);//左移1位
			results[1]=isConnect;

			sendBroadCast();

		}

		private void sendBroadCast() {
			if (results[0]==false&&results[1]==true){
				Intent intent=new Intent();
				intent.setAction(NET_RECOVERY_ACTION);
				mContext.sendBroadcast(intent);
			}
		}
	}

	/**
	 * 下载完成 关闭服务
	 */
	private void stop(){
		es.shutdown();
		stopSelf();
	}


	public static class CheckCallable implements Callable<Boolean>{
		@Override
		public Boolean call() throws Exception {
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10*1000);
			HttpConnectionParams.setSoTimeout(httpParams, 10*1000);
			HttpClient httpclient = new DefaultHttpClient(httpParams);
			String url = serverUrlStr;
			HttpPost httpPost = new HttpPost(url);
			HttpResponse response;
			boolean isConnect = false;
			int count = 0;
			while (count < 2 ) {
				Log.d(TAG, "count========" + count);
				count++;
				try {
					response = httpclient.execute(httpPost);
					int resultCode = response.getStatusLine().getStatusCode();
					Log.d(TAG, "resultCode========" + resultCode);
					if (resultCode == 200 || resultCode == 301 || resultCode == 302) {
						isConnect = true;
						break;
					}
					Thread.sleep(2000);
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return isConnect;
		}
	}
}
